/*
 * @Author: 许旺玉
 * @Description: 封装接口地址
 * @Date: 2020-06-28 13:06:27
 * @LastEditTime: 2020-07-06 16:31:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \靖凯商城\mobile_project\src\api\apiConfig.js
 */

import axios from "axios"
import { Dialog } from 'vant';
import router from '@/router/index.js'
import { Toast } from 'vant';

var httpRequest = axios.create({
  baseURL: '/api',//基本地址
  timeout: 5000,//超时时间
});

httpRequest.interceptors.request.use(function (config) {
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
  return config;
}, function (error) {
  return Promise.reject(error);
});
httpRequest.interceptors.response.use(function (response) {
 Toast.clear()
  return response;
}, function (error) {
  return Promise.reject(error);
});


//请求头设置携带token
httpRequest.interceptors.request.use(
  config => {
    if (localStorage.getItem("token")) {
      config.headers.Authorization = "Bearer " + localStorage.getItem("token")
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

// //token状态码401过期处理
httpRequest.interceptors.response.use(
  response => {
    //  console.log(response);
    return response
  },
  error => {
    if (error.response.status === 401) {
      console.log("请重新登录");
      Dialog.confirm({
        message: '当前状态处于未登录,请前往登录页面进行登录!该弹窗会执行多次',
      }).then(() => {
        router.push("/sign")
      }).catch(() => { })
    }

  }
)

export default httpRequest